const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 帖子收藏模型
const likeSchema = new Schema({
  user_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'User',
    required: true 
  },
  post_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'CommunityPost',
    required: true 
  },
  like_time: { type: Date, default: Date.now },
  like_type: {
    type: String,
    enum: ["post", "course", "product"],
    default: "post"
  }
});
likeSchema.statics.getLikes = async function(user_id, user_name, like_type, offset, limit) {
  try {
    const query = {};
    if (user_id) query.user_id = user_id;
    if (like_type) query.like_type = like_type;
    if (user_name) {
      const { User } = require('../user');
      const parentQuery = {};
      const escapedUserName = escapeRegex(user_name);
      parentQuery.name = { $regex: escapedUserName, $options: 'i' };
      const users = await User.find(parentQuery).lean();
      if (users.length === 0) return { total: 0, rows: [] };
      query.user_id = { $in: users.map(user => user._id) };
    }

    const [result] = await this.aggregate([
      // 1. 匹配查询条件
      { $match: query },

      // 2. 关联查询用户信息
      { $lookup: {
        from: 'users', // 关联的集合名
        localField: 'user_id', // 本地关联字段
        foreignField: '_id', // 关联集合的匹配字段
        as: 'user_info' // 存储关联结果的字段名
      }},

      // 3. 关联查询帖子信息（如果是帖子收藏）
      { $lookup: {
        from: 'communityposts', // 关联的集合名
        localField: 'post_id', // 本地关联字段
        foreignField: '_id', // 关联集合的匹配字段
        as: 'post_info' // 存储关联结果的字段名
      }},

      // 4. 展开关联数据
      { $unwind: {
        path: '$user_info',
        preserveNullAndEmptyArrays: true
      }},
      { $unwind: {
        path: '$post_info',
        preserveNullAndEmptyArrays: true
      }},

      // 5. 统计总数并添加分页
      { $facet: {
        metadata: [{
          $count: 'total' // 统计符合条件的总文档数
        }],
        data: [
          // 投影需要的字段
          { $project: {
            _id: 1,
            user_id: 1,
            post_id: 1,
            like_time: 1,
            like_type: 1,
            user_name: '$user_info.name',
            user_avatar: '$user_info.avatar',
            post_content: '$post_info.content',
          }},
          // 排序
          { $sort: { like_time: -1 } },
          // 分页
          { $skip: Number(offset) },
          { $limit: Number(limit) }
        ]
      }},

      // 6. 整合结果
      { $unwind: '$metadata' },
      { $project: {
        rows: '$data',
        total: '$metadata.total'
      }}
    ]);

    // 处理没有结果的情况
    if (!result || !result.rows) {
      return { rows: [], total: 0 };
    }
    return result;
  } catch (error) {
    console.error('获取点赞列表失败:', error);
    throw new Error('获取点赞列表失败');
  }
}
likeSchema.statics.createLike = async function(likeData = {}) {
  try {
    // 检查是否已点赞
    const existingLike = await this.findOne({
      user_id: likeData.user_id,
      post_id: likeData.post_id,
      like_type: likeData.like_type || 'post'
    });
    if (existingLike) {
      throw new Error('已经点赞过了');
    }
    const like = new this(likeData);
    return await like.save();
  } catch (error) {
    console.error('创建点赞失败:', error);
    throw error;
  }
}
likeSchema.statics.deleteLike = async function(id) {
  try {
    return await this.findByIdAndDelete(id);
  } catch (error) {
    console.error('删除点赞失败:', error);
    throw new Error('删除点赞失败');
  }
}
likeSchema.statics.getStats = async function(user_id) {
  try {
    let query = {};
    if (user_id) query = {$expr: {$eq: [{ $toString: "$user_id" }, user_id.toString()]}};
    return await this.aggregate([
      { $match: query },
      { $group: { _id: "$like_type", count: { $sum: 1 } } }
    ]);
  } catch (error) {
    console.error('获取点赞统计信息失败:', error);
    throw new Error('获取点赞统计信息失败');
  }
}

module.exports = mongoose.model('Like', likeSchema);
